#include <buola/gui/x11/auto.h>

#include <buola/gui/cwindow.h>
#include <buola/gui/x11/cx11window.h>
#include <buola/gui/x11/cx11display.h>
#include <buola/gui/x11/cvisual.h>

namespace buola { namespace gui { namespace x11 {

CVisual::CVisual(CX11Window *pWin)
{
    msg_info() << "aaa " << (long int)pWin << "\n";
    mID=XVisualIDFromVisual(pWin->XVisual());
    msg_info() << "bbb\n";
    mVisualInfo=nullptr;
}

CVisual::CVisual(Visual *pVisual)
{
    mID=XVisualIDFromVisual(pVisual);
    mVisualInfo=nullptr;
}

CVisual::CVisual(VisualID pVisual)
{
    mID=pVisual;
    mVisualInfo=nullptr;
}

CVisual::CVisual(int /*pParam*/,int /*pValue*/)
{
    throw XInternal("not implemented CVisual::CVisual(int,int)");
}

CVisual::~CVisual()
{
    if(mVisualInfo)
        XFree(mVisualInfo);
}

XVisualInfo *CVisual::GetVisualInfo(bool pCopy)
{
    if(!mVisualInfo)
    {
        int lCount;
        XVisualInfo lMatch;
        lMatch.visualid=mID;
        mVisualInfo=XGetVisualInfo(get_default_x11_display()->GetDisplay(),VisualIDMask,
                                                        &lMatch,&lCount);
        if(!lCount)
        {
            throw XInternal("Can't get visual information");
        }
    }

    if(pCopy)
    {
        XVisualInfo *lCopy=mVisualInfo;
        mVisualInfo=nullptr;
        return lCopy;
    }

    return mVisualInfo;
}

static std::wstring ClassToString(int pClass)
{
    switch(pClass)
    {
    case StaticGray:
        return L"StaticGray";
    case GrayScale:
        return L"GrayScale";
    case StaticColor:
        return L"StaticColor";
    case PseudoColor:
        return L"PseudoColor";
    case TrueColor:
        return L"TrueColor";
    case DirectColor:
        return L"DirectColor";
    default:
        return L"unknown";
    }
}

void CVisual::PrintInfo(io::CTextWriter &pWriter)
{
    GetVisualInfo();

    pWriter << "VisualID:      " << mVisualInfo->visualid << "\n";
    pWriter << "Screen:        " << mVisualInfo->screen << "\n";
    pWriter << "Depth:         " << mVisualInfo->depth << "\n";
    pWriter << "Class:         " << ClassToString(mVisualInfo->c_class) << "\n";
    pWriter << "Red mask:      " << mVisualInfo->red_mask << "\n";
    pWriter << "Green mask:    " << mVisualInfo->green_mask << "\n";
    pWriter << "Blue mask:     " << mVisualInfo->blue_mask << "\n";
    pWriter << "Colormap size: " << mVisualInfo->colormap_size << "\n";
    pWriter << "Bits per RGB:  " << mVisualInfo->bits_per_rgb << "\n";
}

/*namespace x11*/ } /*namespace gui*/ } /*namespace buola*/ }
